﻿// using System;
// using System.Collections.Generic;
// using System.Net;
// using System.Net.Sockets;
// using UnityEngine;
// using Yoozoo.Gameplay.Core;
// using Yoozoo.Managers;
// using Yoozoo.Framework.Core;
// using Yoozoo.Framework.Managers;
// using AddressFamily = Yoozoo.Managers.AddressFamily;
//
// namespace Yoozoo.Gameplay.Managers
// {
//     public class NetworkManager : Singleton<NetworkManager>
//     {
//         private const string m_DefaultChannelName = "default";
//         private Yoozoo.Managers.Network m_NetworkManager = null;
//         private Dictionary<string,NetworkEvent> m_NetworkEvents=new Dictionary<string, NetworkEvent>();
//         private Dictionary<string,GTANetworkReconnect> m_NetworkReconnects=new Dictionary<string, GTANetworkReconnect>();
//         private Dictionary<string, INetworkChannelHelper> m_tcpChannelHelper = new Dictionary<string, INetworkChannelHelper>();
//         private static int ReceivePacketCount = 0;
//         private static int ReceivePacketMaxCount = 100000000;
//         private static string _chanelName;
//         /// <summary>
//         /// 获取网络频道数量。
//         /// </summary>
//         public static int NetworkChannelCount
//         {
//             get
//             {
//                 return p_instance.m_NetworkManager.NetworkChannelCount;
//             }
//         }
//         
//         /// <summary>
//         /// 游戏框架组件初始化。
//         /// </summary>
//         public override void Initialize(Options options = null)
//         {
//             m_NetworkManager = new Yoozoo.Managers.Network();
//             MsgSecurityUtils.onSuccessCallBack = SendNetMessageInsImmediately;
//         }
//
//         public override void Update()
//         {
//             if (m_NetworkManager!=null)
//             {
//                 m_NetworkManager.Update(0,Time.deltaTime);
//             }
//
//             foreach (var mNetworkReconnect in m_NetworkReconnects)
//             {
//                 mNetworkReconnect.Value.Update();
//             }
//         }
//
//         public override void Dispose()
//         {
//             var channels = m_NetworkManager.GetAllNetworkChannels();
//             for (int i = 0; i < channels.Length; i++)
//             {
//                 channels[i].Close();
//             }
//             base.Dispose();
//         }
//
//         /// <summary>
//         /// 检查是否存在网络频道。
//         /// </summary>
//         /// <param name="name">网络频道名称。</param>
//         /// <returns>是否存在网络频道。</returns>
//         public static bool HasNetworkChannel(string name)
//         {
//             return p_instance.m_NetworkManager.HasNetworkChannel(name);
//         }
//
//         /// <summary>
//         /// 获取网络频道。
//         /// </summary>
//         /// <param name="name">网络频道名称。</param>
//         /// <returns>要获取的网络频道。</returns>
//         public static INetworkChannel GetNetworkChannel(string name)
//         {
//             return p_instance.m_NetworkManager.GetNetworkChannel(name);
//         }
//
//         /// <summary>
//         /// 获取所有网络频道。
//         /// </summary>
//         /// <returns>所有网络频道。</returns>
//         public static INetworkChannel[] GetAllNetworkChannels()
//         {
//             return p_instance.m_NetworkManager.GetAllNetworkChannels();
//         }
//
//         /// <summary>
//         /// 获取所有网络频道。
//         /// </summary>
//         /// <param name="results">所有网络频道。</param>
//         public static void GetAllNetworkChannels(List<INetworkChannel> results)
//         {
//             p_instance.m_NetworkManager.GetAllNetworkChannels(results);
//         }
//
//         /// <summary>
//         /// 创建网络频道。
//         /// </summary>
//         /// <param name="name">网络频道名称。</param>
//         /// <param name="serviceType">网络服务类型。</param>
//         /// <param name="networkChannelHelper">网络频道辅助器。</param>
//         /// <returns>要创建的网络频道。</returns>
//         public static INetworkChannel CreateNetworkChannel(string name, ServiceType serviceType, INetworkChannelHelper networkChannelHelper)
//         {
//             var channel= p_instance.m_NetworkManager.CreateNetworkChannel(name, serviceType, networkChannelHelper);
//             channel.HeartBeatInterval = 0; //lua层已经处理了心跳
//             NetworkEvent networkEvent = null;
//             if(p_instance.m_NetworkEvents.ContainsKey(name))
//             {
//                 networkEvent = p_instance.m_NetworkEvents[name];
//             }
//             else
//             {
//                 networkEvent = new NetworkEvent();
//                 p_instance.m_NetworkEvents.Add(name, networkEvent);
//             }
//             channel.RegisterHandler(networkEvent.OnPacket);
//             
//             var networkReconnect=new GTANetworkReconnect();
//             networkReconnect.Initialize(channel);
//             p_instance.m_NetworkReconnects.Add(name,networkReconnect);
//             if (p_instance.m_tcpChannelHelper.ContainsKey(name))
//             {
//                 p_instance.m_tcpChannelHelper.Remove(name);
//             }
//             p_instance.m_tcpChannelHelper.Add(name, networkChannelHelper);
//             return channel;
//         }
//
//         public static void Connect(string ip,int port,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             var channel=CreateNetworkChannel(channelName, ServiceType.Tcp, new GTATcpChannelHelper());
//             IPAddress ipAddress;
//             if (!IPAddress.TryParse(ip, out ipAddress))
//             {
//                 if (Socket.OSSupportsIPv6)
//                 {
//                     if (ip == "localhost")
//                     {
//                         ipAddress = IPAddress.IPv6Loopback;
//                     }
//                     else
//                     {
//                         ipAddress = ResolveAddress(ip, System.Net.Sockets.AddressFamily.InterNetworkV6);
//                     }
//                 }
//                 if (ipAddress == null)
//                 {
//                     ipAddress = ResolveAddress(ip, System.Net.Sockets.AddressFamily.InterNetwork);
//                 }
//             }
//             if (ipAddress == null)
//             {
//                 throw new Exception("Invalid address: " + ip);
//             }
//             channel.Connect(ipAddress, port);
//         }
//         
//         private static IPAddress ResolveAddress(string hostStr, System.Net.Sockets.AddressFamily addressFamily)
//         {
// #if NETCORE
//             var hostTask = Dns.GetHostEntryAsync(hostStr);
//             hostTask.Wait();
//             var host = hostTask.Result;
// #else
//             var host = Dns.GetHostEntry(hostStr);
// #endif
//             foreach (IPAddress ip in host.AddressList)
//             {
//                 if (ip.AddressFamily == addressFamily)
//                 {
//                     return ip;
//                 }
//             }
//             return null;
//         }
//
//         
//         public static void ConnectPressure(string ip,int port,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             var channel=CreateNetworkChannel(channelName, ServiceType.Tcp, new GTATcpChannelHelper());
//             channel.Connect(IPAddress.Parse(ip), port);
//         }
//         
//         public static bool SendBytes(int msgId,byte[] bytes, bool isGameProto, string channelName =null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             if(p_instance.m_tcpChannelHelper.ContainsKey(channelName))
//             {
//                 GTATcpChannelHelper helper = p_instance.m_tcpChannelHelper[channelName] as GTATcpChannelHelper;
//                 helper.isGameProto = isGameProto;
//             }
//             var channel=p_instance.m_NetworkManager.GetNetworkChannel(channelName);
//             if (channel.Connected)
//             {
//                 if (Debug.isDebugBuild && SDKManager.protoTest)
//                 {
// #if UNITY_ANDROID && !UNITY_EDITOR
//                     _chanelName = channelName;
//                     MsgSecurityUtils.Instance.SendMsg(msgId,bytes);
//                     return true;
// #endif
//                 }
//
//                 channel.Send(new Packet()
//                 {
//                     msgId = msgId,
//                     message = bytes
//                 });
//                 return true;
//             }
//             else
//             {
//                 return false;
//             }            
//         }
//         
//         public static bool SendBytesCallback(int msgId,byte[] bytes, bool isGameProto, Action<object> receiveCallback,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             if(p_instance.m_tcpChannelHelper.ContainsKey(channelName))
//             {
//                 GTATcpChannelHelper helper = p_instance.m_tcpChannelHelper[channelName] as GTATcpChannelHelper;
//                 helper.isGameProto = isGameProto;
//             }
//             var channel=p_instance.m_NetworkManager.GetNetworkChannel(channelName);
//             if (channel.Connected)
//             {
//                 if (Debug.isDebugBuild && SDKManager.protoTest)
//                 {
//                     #if UNITY_ANDROID && !UNITY_EDITOR
//                     _chanelName = channelName;
//                     MsgSecurityUtils.Instance.SendMsg(msgId,bytes);
//                     return true;
//                     #endif
//                 }
//                 channel.Send(new Packet()
//                 {
//                     msgId = msgId,
//                     message = bytes
//                 });
//                 p_instance.m_NetworkEvents[channelName].AddListener(msgId, receiveCallback,true);
//                 return true;
//             }
//             else
//             {
//                 return false;
//             }
//         }
//         
//         private void SendNetMessageInsImmediately(int msgId, byte[] bytes)
//         {
//             var channel=p_instance.m_NetworkManager.GetNetworkChannel(_chanelName);
//             channel.Send(new Packet()
//             {
//                 msgId = msgId,
//                 message = bytes
//             });
//         }
//         public static void SendMessage(int msgId, object msg,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             if (p_instance.m_tcpChannelHelper.ContainsKey(channelName))
//             {
//                 GTATcpChannelHelper helper = p_instance.m_tcpChannelHelper[channelName] as GTATcpChannelHelper;
//                 helper.isGameProto = false;
//             }
//             var channel=p_instance.m_NetworkManager.GetNetworkChannel(channelName);
//             if (channel.Connected)
//             {
//                 channel.Send(new Packet()
//                 {
//                     msgId = msgId,
//                     message = msg
//                 });
//             }
//         }
//         public static void SendMessageCallback(int msgId, object msg,Action<object> receiveCallback,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             var channel=p_instance.m_NetworkManager.GetNetworkChannel(channelName);
//             if (channel.Connected)
//             {
//                 channel.Send(new Packet()
//                 {
//                     msgId = msgId,
//                     message = msg
//                 });
//                 p_instance.m_NetworkEvents[channelName].AddListener(msgId, receiveCallback,true);
//             }
//         }
//
//         public static void AddListener(int msgId,Action< object> callback,bool isSingle,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             NetworkEvent networkEvent = null;
//             if (p_instance.m_NetworkEvents.ContainsKey(channelName))
//             {
//                 networkEvent = p_instance.m_NetworkEvents[channelName];
//             }
//             else
//             {
//                 networkEvent = new NetworkEvent();
//                 p_instance.m_NetworkEvents.Add(channelName, networkEvent);
//             }
//
//             networkEvent.AddListener(msgId, callback,isSingle);
//         }
//
//         public static void RemoveListener(int msgId, Action<object> callback,string channelName=null)
//         {
//             if (string.IsNullOrEmpty(channelName))
//             {
//                 channelName = m_DefaultChannelName;
//             }
//             p_instance.m_NetworkEvents[channelName].RemoveListener(msgId, callback);
//         }
//
//         public static int GetReceivePacketCount(string name = null)
//         {
//             if (string.IsNullOrEmpty(name))
//             {
//                 name = m_DefaultChannelName;
//             }
//             int total = 0;
//             var channel = p_instance.m_NetworkManager.GetNetworkChannel(name);
//             if (channel != null)
//             {
//                 total = ReceivePacketCount + channel.ReceivedPacketCount;
//             }
//             return total;
//         }
//
//         /// <summary>
//         /// 销毁网络频道。
//         /// </summary>
//         /// <param name="name">网络频道名称。</param>
//         /// <returns>是否销毁网络频道成功。</returns>
//         public static bool DestroyNetworkChannel(string name = null)
//         {
//             if (string.IsNullOrEmpty(name))
//             {
//                 name = m_DefaultChannelName;
//             }
// //            if (p_instance.m_NetworkEvents.ContainsKey(name))
// //            {
// //                p_instance.m_NetworkEvents.Remove(name);
// //            }
//
//             if (p_instance.m_NetworkReconnects.ContainsKey(name))
//             {
//                 p_instance.m_NetworkReconnects.Remove(name);
//             }
//
//             var channel = p_instance.m_NetworkManager.GetNetworkChannel(name);
//             if (channel != null)
//             {
//                 ReceivePacketCount += channel.ReceivedPacketCount;
//                 if (ReceivePacketCount > ReceivePacketMaxCount)
//                 {
//                     ReceivePacketCount = ReceivePacketCount - ReceivePacketMaxCount;
//                 }
//             }
//             return p_instance.m_NetworkManager.DestroyNetworkChannel(name);
//         }
//     }
// }
// }
